﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace FileTranslator
{
    public abstract class Loader : IDisposable
    {
        // 存储目标路径
        public string TargetPath { get; set; }
        // 数据存放容器
        public DataContainer DataVessel { get; set; }

        protected DataTable csvTable;
        public DataTable ResultTable
        {
            get
            {
                return csvTable;
            }
        }

        // 读取内容
        public bool Load()
        {
            isClosed = false;

            if (VerifyIfCanLoad() == false)
            {
                return false;
            }

            BeforeLoadWork();
            DoLoad();
            AfterLoadWork();

            return true;
        }

        protected virtual void BeforeLoadWork() { }
        protected virtual void AfterLoadWork() { }
        protected abstract void DoLoad();

        // 针对GroupBy进行分组
        protected abstract void DoGroupBy();

        protected virtual bool VerifyIfCanLoad()
        {
            return TargetPath != null && DataVessel != null;
        }

        // 关闭加载器相关代码
        private bool isClosed;
        
        public void Dispose() { InnerDispose(); }
        public void Close() { Dispose(); }

        protected virtual void BeforeCloseWork() { }
        protected virtual void AfterCloseWork() { }
        private void InnerDispose()
        {
            if (isClosed == false)
            {
                // TODO: exception handle
                BeforeCloseWork();
                DataVessel.Clear();
                AfterCloseWork();

                isClosed = true;
            }
        }
    }
}
